<?php

namespace app\api\model;

use app\api\service\IdCheck;
use app\api\service\SendNotice;
use fast\Random;
use think\Config;
use think\Db;
use think\File;
use think\Log;
use think\Model;

class Basic extends Model
{
    public $redis;
    public $params;
    public $config;
    public $code;
    public $applets;
    public $ip;
    public $token;
    public $file = [];

    public function __construct($data = [])
    {
        header('Access-Control-Allow-Origin:*');//允许所有来源访问

        parent::__construct($data);

        $this->redis = new \think\cache\driver\Redis();
        $this->params = $_REQUEST;

        $this->params['source'] = isset($this->params['source']) ? $this->params['source'] : 0;
        $this->params['login_type'] = isset($this->params['login_type']) ? $this->params['login_type'] : 0;

        $this->config = Config::get('Config');
        $this->code = $this->config['code'];
        $this->applets = $this->config['applets'];
        $this->checkParams($this->params);
        $this->ip = $_SERVER['REMOTE_ADDR'];
    }

    /**
     * 请求数据验证方法
     */
    private function checkParams($data)
    {
        if (!isset($data['source'])) {
            die(\GuzzleHttp\json_encode(['code' => $this->code['Error'], 'msg' => '缺少请求来源数据']));
        }
        if (!isset($data['login_type'])) {
            die(\GuzzleHttp\json_encode(['code' => $this->code['Error'], 'msg' => '缺少登录必要参数信息']));
        }
        if ($data['login_type']) {
            if (!isset($data['token'])) {
                die(\GuzzleHttp\json_encode(['code' => $this->code['Error'], 'msg' => '缺少token必要参数']));
            }
            $where = [
                'token' => $data['token']
            ];

            $info = User::getInstance()->getUserInfo($where);
            if (empty($info)) {
                die(\GuzzleHttp\json_encode(['code' => $this->code['noRegister'], 'msg' => '账户未注册']));
            }
            if (in_array($info['status'], [2, 3])) {
                die(\GuzzleHttp\json_encode(['code' => $this->code['cancelLogin'], 'msg' => '账户状态禁用']));
            }
            if ($data['token'] !== $info['token']) {
                die(\GuzzleHttp\json_encode(['code' => $this->code['noLogin'], 'msg' => '账户未登录']));
            }
            $this->redis->set('user_' . $info['uid'], $info);
        }
    }

    public function getToken()
    {
        $tokenMd5 = strtoupper(base64_encode(md5($this->token)));
        $this->token = $tokenMd5;
    }

    /**
     * 获取上传的文件信息
     * @access public
     * @param string|array $name 名称
     * @return null|array|\think\File
     */
    public function file($name = '')
    {
        if (empty($this->file)) {
            $this->file = isset($_FILES) ? $_FILES : [];
        }
        if (is_array($name)) {
            return $this->file = array_merge($this->file, $name);
        }
        $files = $this->file;
        if (!empty($files)) {
            // 处理上传文件
            $array = [];
            foreach ($files as $key => $file) {
                if (is_array($file['name'])) {
                    $item = [];
                    $keys = array_keys($file);
                    $count = count($file['name']);
                    for ($i = 0; $i < $count; $i++) {
                        if (empty($file['tmp_name'][$i]) || !is_file($file['tmp_name'][$i])) {
                            continue;
                        }
                        $temp['key'] = $key;
                        foreach ($keys as $_key) {
                            $temp[$_key] = $file[$_key][$i];
                        }
                        $item[] = (new File($temp['tmp_name']))->setUploadInfo($temp);
                    }
                    $array[$key] = $item;
                } else {
                    if ($file instanceof File) {
                        $array[$key] = $file;
                    } else {
                        if (empty($file['tmp_name']) || !is_file($file['tmp_name'])) {
                            continue;
                        }
                        $array[$key] = (new File($file['tmp_name']))->setUploadInfo($file);
                    }
                }
            }
            if (strpos($name, '.')) {
                list($name, $sub) = explode('.', $name);
            }
            if ('' === $name) {
                // 获取全部文件
                return $array;
            } elseif (isset($sub) && isset($array[$name][$sub])) {
                return $array[$name][$sub];
            } elseif (isset($array[$name])) {
                return $array[$name];
            }
        }
        return;
    }

    /**
     * 数据返回形式 0 die   1  return
     */
    public function jsonType($data, $type = 0)
    {
        if (empty($type)) {
            die(\GuzzleHttp\json_encode($data));
        } else {
            return $data;
        }
    }

    /**
     * 获取订单流水号
     */
    public function getNumId()
    {
        $numId = date("ymd", time()) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
        return substr_replace($numId, 'R', 0, 1);
    }

    /**
     * 获取地区
     */
    public function getAreaName($id)
    {
        $where = [
            'id' => ['eq', $id],
        ];
        $areaName = Db::name('area')->where($where)->value('name');
        return $areaName;
    }

    public function getLogisticsCompany()
    {
        return [
            'jd'  => '京东快递',
            '011' => '百世汇通',
            '022' => '韵达快递',
            '033' => '中通快递',
            '044' => '顺丰快递',
            '055' => '圆通快递',
            '066' => '汇通快递',
        ];
    }

    /**
     * 上传文件
     */
    public function uploadFile()
    {
        $file = $this->file('file');

        if (empty($file)) {
            die(json_encode(['code' => $this->code['Error'], 'msg' => 'No file upload or server upload limit exceeded']));
        }
        //判断是否已经存在附件
        $sha1 = $file->hash();
        $upload = Config::get('upload');

        preg_match('/(\d+)(\w+)/', $upload['maxsize'], $matches);
        $type = strtolower($matches[2]);
        $typeDict = ['b' => 0, 'k' => 1, 'kb' => 1, 'm' => 2, 'mb' => 2, 'gb' => 3, 'g' => 3];
        $size = (int)$upload['maxsize'] * pow(1024, isset($typeDict[$type]) ? $typeDict[$type] : 0);
        $fileInfo = $file->getInfo();
        $suffix = strtolower(pathinfo($fileInfo['name'], PATHINFO_EXTENSION));
        $suffix = $suffix ? $suffix : 'file';

        $mimetypeArr = explode(',', strtolower($upload['mimetype']));
        $typeArr = explode('/', $fileInfo['type']);

        //验证文件后缀
        if ($upload['mimetype'] !== '*' &&
            (
                !in_array($suffix, $mimetypeArr)
                || (stripos($typeArr[0] . '/', $upload['mimetype']) !== false && (!in_array($fileInfo['type'], $mimetypeArr) && !in_array($typeArr[0] . '/*', $mimetypeArr)))
            )
        ) {
            die(\GuzzleHttp\json_encode(['code' => $this->code['Error'], 'msg' => 'Uploaded file format is limited']));
        }
        $replaceArr = [
            '{year}' => date("Y"),
            '{mon}' => date("m"),
            '{day}' => date("d"),
            '{hour}' => date("H"),
            '{min}' => date("i"),
            '{sec}' => date("s"),
            '{random}' => Random::alnum(16),
            '{random32}' => Random::alnum(32),
            '{filename}' => $suffix ? substr($fileInfo['name'], 0, strripos($fileInfo['name'], '.')) : $fileInfo['name'],
            '{suffix}' => $suffix,
            '{.suffix}' => $suffix ? '.' . $suffix : '',
            '{filemd5}' => md5_file($fileInfo['tmp_name']),
        ];
        $savekey = $upload['savekey'];
        $savekey = str_replace(array_keys($replaceArr), array_values($replaceArr), $savekey);

        $uploadDir = substr($savekey, 0, strripos($savekey, '/') + 1);
        $fileName = substr($savekey, strripos($savekey, '/') + 1);

        $splInfo = $file->validate(['size' => $size])->move(ROOT_PATH . '/public' . $uploadDir, $fileName);
        if ($splInfo) {
            $imagewidth = $imageheight = 0;
            if (in_array($suffix, ['gif', 'jpg', 'jpeg', 'bmp', 'png', 'swf'])) {
                $imgInfo = getimagesize($splInfo->getPathname());
                $imagewidth = isset($imgInfo[0]) ? $imgInfo[0] : $imagewidth;
                $imageheight = isset($imgInfo[1]) ? $imgInfo[1] : $imageheight;
            }
            $file_url = $uploadDir . $splInfo->getSaveName();
            return $file_url;
        } else {
            // 上传失败获取错误信息
            die(json_encode(['code' => $this->code['Error'], 'msg' => $file->getError()]));
        }
    }

    /**
     * 打印结果信息
     */
    public function printEcho($data)
    {
        echo '<pre>';
        print_r($data);die;
    }
}